package com.xxx.client.loadbalance;

import com.xxx.client.handler.RemoteCallClient;
import com.xxx.client.registry.ChannelInfo;

import java.util.Map;
import java.util.Random;

/**
 * Created by louisyuu on 2020/4/30 上午10:45
 */

/**
 * 随机轮询
 */
public class RoundRobinLoadbalancer implements Loadbalancer {


    @Override
    public ChannelInfo getClient() {
        Map<String, ChannelInfo> availableServers = RemoteCallClient.getInstance().getAvailableServers();

//        System.out.println("==========Round robin available servers are "+availableServers.size());

        if (availableServers.isEmpty()) {
            return null;
        }
        int selected = new Random().nextInt(availableServers.size());
        int i = 0;
        for (Map.Entry<String, ChannelInfo> entry : availableServers.entrySet()) {
            if (i == selected) {
                return entry.getValue();
            }
            i++;
        }
        return null;
    }
}
